<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :align-center="true" width="70%" title="开票管理">
    <el-form
      ref="billFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="120px"
      label-suffix=" :"
      :hide-required-asterisk="dialogData.isView"
    >
      <el-row :gutter="20">
        <el-col :span="10">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>开票基本信息</span>
              </div>
            </template>
            <el-form-item label="抬头类型">
              <el-select
                @change="handleBilltypeChange"
                style="width: 100%"
                v-model="dialogData.itemInfo.billRiseId"
                placeholder="请选择发票抬头"
              >
                <el-option v-for="item in dialogData.billRiseDatas" :key="item.id" :label="item.companyName" :value="item.id">
                  <span style="float: left">{{ item.companyName }}</span>
                  <el-tag class="rise-item" type="primary">
                    {{ filterEnum(item.type, billType) }}
                  </el-tag>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="抬头类型">
              <el-tag type="primary"> {{ filterEnum(dialogData.itemInfo.billType, billType) }}</el-tag>
            </el-form-item>
            <el-form-item :label="dialogData.itemInfo.billType == 1 ? '发票抬头' : '姓名'">
              <el-input v-model="dialogData.itemInfo.riseName" readonly></el-input>
            </el-form-item>
            <el-form-item :label="dialogData.itemInfo.billType == 1 ? '公司税号' : '身份证号'">
              <el-input v-model="dialogData.itemInfo.riseNo" readonly></el-input>
            </el-form-item>
            <el-divider></el-divider>
            <el-form-item label="发票类型">
              <el-tag type="primary"> {{ filterEnum(dialogData.itemInfo.invoiceType, invoiceType) }}</el-tag>
            </el-form-item>
            <el-form-item label="发票金额">
              <el-input-number
                v-model="dialogData.itemInfo.billAmt"
                :max="dialogData.maxAmt||0"
                :min="0"
                style="width: 100%"
                :precision="2"
                placeholder="发票金额"
              >
              </el-input-number>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="dialogData.itemInfo.billNote"
                maxlength="100"
                show-word-limit
                :rows="4"
                type="textarea"
                placeholder="备注"
              ></el-input>
            </el-form-item>
            <el-form-item label="收票邮箱">
              <el-input v-model="dialogData.itemInfo.billEmail" maxlength="50" show-word-limit placeholder="收票邮箱"></el-input>
            </el-form-item>
            <el-form-item label="收票地址">
              <el-input
                v-model="dialogData.itemInfo.billAddress"
                maxlength="100"
                show-word-limit
                placeholder="收票地址"
              ></el-input>
            </el-form-item>
            <el-alert title="请认真核对您的收票地址及邮箱地址，谨防发票丢失！" type="warning" show-icon :closable="false" />
          </el-card>
        </el-col>
        <el-col :span="14">
          <el-card>
            <template #header>
              <div class="can-bill-wrapper">
                <div class="opt-box">
                  <el-select
                    size="large"
                    style="width: 100%"
                    v-model="dialogData.itemInfo.invoiceType"
                    placeholder="请选择开票类型"
                  >
                    <el-option v-for="item in invoiceType" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </div>
                <div class="sum-box">
                  <span class="sum-title">开票金额:</span>
                  <span class="sum-info">{{ dialogData.itemInfo.billAmt }}</span>
                </div>
              </div>
            </template>
            <div class="table-opt-box">
              <el-button type="primary" :icon="CirclePlus" @click="handleOpenDialog" :disabled="dialogData.isView">
                添加开票项
              </el-button>
            </div>
            <el-table :data="dialogData.tableData" style="width: 100%">
              <el-table-column type="selection" width="55" />
              <el-table-column label="岗位时间" prop="optDate" width="130">
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <el-icon><timer /></el-icon>
                    <span style="margin-left: 10px">{{ scope.row.optDate }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="发票类型" prop="invoiceType" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.invoiceType === sysEnum.ONE ? 'primary' : 'danger'">
                    {{ filterEnum(scope.row.invoiceType, invoiceShortType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="金额" prop="totalAmt"  width="80" ></el-table-column>
              <el-table-column label="项目" prop="jobTitle">
                <template #default="scope">
                  <div class="job-title-box">
                    <span class="title-info">{{ scope.row.jobTitle }}</span>
                  </div>
                  <div class="job-type-box">
                    <el-tag :type="'primary'" size="small">
                      {{ scope.row.jobTypeName}}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="right" width="80">
                <template #default="scope">
                  <el-button size="small" type="danger" @click="handleDelete(scope.$index)"> 删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading">确定</el-button>
    </template>
  </el-dialog>
  <CanBillDialog ref="dialogRef" @refresh-data="handleRefreshData" />
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getOptTitle, OptEnum, sysEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { getBillInfoApi, getBillRisesApi, getCanBillJobsByIdsApi, saveBillApi } from "@/api/modules/cpyjob/bill";
import { BillEntity } from "@/biz/interface/BillType";
import { filterEnum } from "@/utils";
import { billType, invoiceType, invoiceShortType } from "@/biz/datas/appData";
import { Timer, CirclePlus } from "@element-plus/icons-vue";
import CanBillDialog from "./CanBillDialog.vue";

//页面的数据
interface flexjobAbnormalDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  //是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  // 当前的开票明细
  tableData: any[];
  // 发票抬头
  billRiseDatas: any[];
  // 开票最大金额
  maxAmt?:number;
  //当前的数据对象
  itemInfo: BillEntity;
  //其它的数据都继续在这里加
}

//提交按钮，避免多次提交
const btnLoading = ref(false);
//弹出框的参数
const dialogVisible = ref(false);
//当前表单数据在这里初始化
const dialogData = reactive<flexjobAbnormalDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  tableData: [],
  billRiseDatas: [],
  maxAmt:0,
  itemInfo: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;
  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.title = getOptTitle(dialogData.optType);

  initItemInfo();
  if (dialogData.rowData && dialogData.rowData.id) {
    getItemInfo(dialogData.rowData.id);
  }

  dialogVisible.value = true;
};

//初始化页面的数据
const initItemInfo = (): void => {
  dialogData.tableData = [];
  dialogData.itemInfo = {
    invoiceType: 1
  };
};
//获取当前数据的详情，直接调用接口获取数据
const getItemInfo = async (id: string) => {
  if (id) {
    // console.log(id);
    let { data } = await getBillInfoApi({ id });
    dialogData.itemInfo = data as unknown as BillEntity;
    dialogData.tableData = data.items || [];
  }
};

//数据较验
const rules = reactive({
  billNo: [{ required: true, message: "请填写开票单号", trigger: "blur" }]
});

// 提交数据（新增/编辑）
const billFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  billFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (!dialogData.itemInfo || !dialogData.tableData) {
        ElMessage.error({ message: `开票项不能为空` });
      }

      // 开票明细
      dialogData.itemInfo.itemIds = dialogData.tableData.map(item => item.id) || [];

      //提交数据
      let res = await saveBillApi({
        ...dialogData.itemInfo
      });
      if (res.data) {
        ElMessage.success({ message: `开票信息添加完成！` });
        //刷新列表数据
        // eslint-disable-next-line vue/custom-event-name-casing
        emits("refresh-list");
        dialogVisible.value = false;
      }
    } catch (error) {
    } finally {
      btnLoading.value = false;
    }
  });
};

// 类型发生变化
const handleBilltypeChange = val => {
  // console.log("发票抬头变化，要去获取抬头，填充数据", val, dialogData.itemInfo.billType);
  if (val) {
    let billrise = dialogData.billRiseDatas.find(item => item.id === val) || {};
    // console.log("匹配出的发票抬头", billrise);
    dialogData.itemInfo.billType = billrise.type;
    dialogData.itemInfo.riseName = billrise.companyName;
    dialogData.itemInfo.riseNo = billrise.billNo;
  }
};

// 移除一条开票明细
const handleDelete = ( idx:number ) => {
  // console.log("移除一条", idx);
  if (dialogData.tableData) {
    // 去掉一个
    dialogData.tableData.splice(idx,1);
  }
};

// 打开 dialog(新增、查看、编辑)
const dialogRef = ref();
const handleOpenDialog = () => {
  if (dialogData.itemInfo.invoiceType) {
    let params = {
      invoiceType: dialogData.itemInfo.invoiceType
    };
    // console.log("开票弹窗", params);
    dialogRef.value.acceptParams(params);
  } else {
    ElMessage.error({ message: "请选择开票的类型" });
  }
};

const handleRefreshData = (data: any[]) => {
  // console.log("当前选择的ids", ids);
  if (data) {
    // 通过 ids 获取开票项目
    const eids =
      (dialogData.itemInfo?.items || []).map(item => {
        item.id;
      }) || [];
    // 和发票当前的已有的开票项合并， 去掉重复的项
    const allids = new Set([...eids, ...data.ids]);
    // 查找所有的可开票的明细
    if (allids) {
      getCanBillJobsByIdsApi({ ids: [...allids] }).then(res => {
        let datas = res?.data || [];
        dialogData.tableData = datas;
        // console.log(dialogData.tableData);
        // 计算开票总和
        dialogData.itemInfo.billAmt = dialogData.tableData.reduce((sum, item) => sum + item.totalAmt, 0);
        dialogData.maxAmt =  dialogData.itemInfo.billAmt;
      });
    }
  }
};

//初始化一些参数
onMounted(() => {
  getBillRisesApi().then(res => {
    // console.log("获取发票抬用户列表:", res);
    if (res && res.data) {
      dialogData.billRiseDatas = res.data.list || [];
    }
  });
});

//页面事件
const emits = defineEmits(["refresh-list"]);

//页面参数
defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
.can-bill-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .opt-box {
    flex: 1;
    // border: 1px solid red;
  }
  .sum-box {
    width: 300px;
    height: 100%;

    margin-left: 10px;
    // border: 1px solid red;

    display: flex;
    justify-content: flex-end;
    align-items: center;

    .sum-title {
      font-size: 0.8rem;
      font-weight: 400;
      color: var(--el-color-info);
    }

    .sum-info {
      font-size: 2rem;
      font-weight: 600;
      color: var(--el-color-danger);
      margin-left: 12px;
    }
  }
}

.table-opt-box {
  margin-bottom: 10px;
}

.rise-item {
  float: right;
  color: var(--el-text-color-secondary);
  font-size: 13px;
  margin-top: 5px;
}

</style>
